package com.valuedaas.schoolsafety.common.config;

import cn.hutool.core.util.StrUtil;
import com.valuedaas.schoolsafety.common.config.spring.AutoWiringSpringBeanJobFactory;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.text.ParseException;
import java.util.Properties;

/**
 * Quartz 集群（基于mongodb数据库）
 */
@Configuration
@EnableScheduling
public class QuartzConfig {

    @Value("${spring.data.mongodb.uri}")
    private String mongoUri;

    @Value("${quartz.isClustered}")
    private String isClustered;

    @Bean("quartzPropertyies")
    public Properties getPropertyies() {
        Properties properties = new Properties();
        properties.setProperty("org.quartz.jobStore.mongoUri", mongoUri);// 配置mongodb的集群地址
        properties.setProperty("org.quartz.jobStore.class", "com.novemberain.quartz.mongodb.MongoDBJobStore");
        properties.setProperty("org.quartz.jobStore.dbName", StrUtil.subAfter(mongoUri, "/", true));// 配置数据库名
        properties.setProperty("org.quartz.jobStore.collectionPrefix", "task");// 配置表名前缀
        properties.setProperty("org.quartz.jobStore.jobTimeoutMillis", "7200000"); //60分钟
        properties.setProperty("org.quartz.jobStore.triggerTimeoutMillis", "7200000");// 配置触发器锁的过期时间 60分钟
        properties.setProperty("org.quartz.threadPool.threadCount", "2");// 线程数量
        properties.setProperty("org.quartz.jobStore.isClustered", isClustered); // 是否是集群
        properties.setProperty("org.quartz.scheduler.instanceId", "AUTO");
        properties.setProperty("org.quartz.scheduler.instanceName", "clusterName"); // ????
        properties.setProperty("org.quartz.jobStore.clusterCheckinInterval", "5000");// 检测mongodb触发器状态的间隔时间 5秒
        return properties;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws ParseException {
        SchedulerFactoryBean sfBean = new SchedulerFactoryBean();
        // ClassPathResource cpr = new ClassPathResource("quartz.properties");
        // sfBean.setConfigLocation(cpr); //注释掉的代码是当用.properties文件配置的时候用的,可以和上边的配置函数等价
        sfBean.setQuartzProperties(getPropertyies());
        sfBean.setOverwriteExistingJobs(true); // 动态更新
        sfBean.setStartupDelay(10);
        // 解决 Job类中无法使用 Autowired 依赖注入问题
        sfBean.setJobFactory(autoWiringSpringBeanJobFactory());
        sfBean.setApplicationContextSchedulerContextKey("redsteward");
        return sfBean;
    }

    @Bean
    public AutoWiringSpringBeanJobFactory autoWiringSpringBeanJobFactory() {
        return new AutoWiringSpringBeanJobFactory();
    }

    @Bean
    public Scheduler scheduler() throws ParseException {
        return schedulerFactoryBean().getScheduler();
    }

}